package cn.cdiothree.service.impl;

import cn.cdiothree.DTO.OrderDTO;
import cn.cdiothree.dao.ProductOrderMapper;
import cn.cdiothree.dao.UserMapper;
import cn.cdiothree.dataobject.ProductOrder;
import cn.cdiothree.enums.ResultEnum;
import cn.cdiothree.exception.SellException;
import cn.cdiothree.service.BuyerService;
import cn.cdiothree.service.ProductOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.stereotype.Service;

/**
 * 卖家操作
 */
@Service
@Slf4j
public class BuyerServiceImpl  implements BuyerService {

    @Autowired
    private ProductOrderService productOrderService;

    /**
     * 查找订单
     * @param userId
     * @param orderId
     * @return
     */
    @Override
    public OrderDTO findOrderOne(Integer userId, String orderId) {
        log.info("查找订单，用户id{}，订单id{}",userId,orderId);
        return checkOrderOwner(userId,orderId);
    }

    /**
     * 取消订单
     * @param userId
     * @param orderId
     * @return
     */
    @Override
    public OrderDTO cancelOrder(Integer userId, String orderId) {
        OrderDTO orderDTO =checkOrderOwner(userId,orderId);
        if (orderDTO==null){
            log.error("【取消订单】查询不到该订单，orderId={}",orderId);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return productOrderService.cancel(orderDTO);
    }

    private OrderDTO checkOrderOwner(Integer userId, String orderId){
        OrderDTO orderDTO=productOrderService.findOne(orderId);
        if (orderDTO==null){
            return null;
        }
        //判断是否是自己的订单
        if (!orderDTO.getUserId().equals(userId)){
            log.error("【查询订单】订单的userId不一致，userId={},orderDTO={}",userId,orderDTO);
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
